import type { EChartsOption } from 'echarts'
import type { Ref } from 'vue'

import { tryOnUnmounted, useDebounceFn, useTimeoutFn } from '@vueuse/core'
import { computed, nextTick, ref, unref } from 'vue'

import echarts from '../lib'
import { useEventListener } from './useEventListener'

type Fn = () => void

export function useECharts(elRef: Ref<HTMLDivElement>, theme: 'light' | 'dark' | 'default' = 'default') {
  let chartInstance: echarts.ECharts | null = null
  let resizeFn: Fn = resize
  const cacheOptions = ref({}) as Ref<EChartsOption>
  let removeResizeFn: Fn = () => {
    //
  }

  resizeFn = useDebounceFn(resize, 200)

  const getOptions = computed(() => {
    if (theme !== 'dark') return cacheOptions.value

    return {
      backgroundColor: 'transparent',
      ...cacheOptions.value
    } as EChartsOption
  })

  function initCharts(t = theme) {
    const el = unref(elRef)
    if (!el || !unref(el)) return

    chartInstance = echarts.init(el, t)
    const { removeEvent } = useEventListener({
      el: window,
      name: 'resize',
      listener: resizeFn
    })
    removeResizeFn = removeEvent
  }

  function setOptions(options: EChartsOption, clear = true) {
    cacheOptions.value = options
    return new Promise((resolve) => {
      if (unref(elRef)?.offsetHeight === 0) {
        useTimeoutFn(() => {
          setOptions(unref(getOptions))
          resolve(null)
        }, 30)
      }
      nextTick(() => {
        useTimeoutFn(() => {
          if (!chartInstance) {
            initCharts()

            if (!chartInstance) return
          }
          clear && chartInstance?.clear()

          chartInstance?.setOption(unref(getOptions))
          resolve(null)
        }, 30)
      })
    })
  }

  function resize() {
    chartInstance?.resize({
      animation: {
        duration: 300,
        easing: 'quadraticIn'
      }
    })
  }

  tryOnUnmounted(() => {
    if (!chartInstance) return
    removeResizeFn()
    chartInstance.dispose()
    chartInstance = null
  })

  function getInstance(): echarts.ECharts | null {
    if (!chartInstance) initCharts()

    return chartInstance
  }

  return {
    setOptions,
    resize,
    echarts,
    getInstance
  }
}
